﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SharpTRI
{
    class Game
    {
	    int mLight;
        int mCamera;
        int mPlane;

        Player mPlayer;
        List<Bot> bots = new List<Bot>();

        public Game(int width, int height, int depth)
        {
            Xors3D.xGraphics3D(width, height, depth);
            Xors3D.xSetBuffer(Xors3D.xBackBuffer());

            InitScene();
            CreateCharacters();
        }

        void InitScene()
        {
            mLight = Xors3D.xCreateLight();
            Xors3D.xTurnEntity(mLight, 45, 45, 45);

            mPlane = Xors3D.xCreatePoly(4);
            Xors3D.xEntityColor(mPlane, 20, 20, 20);
            Xors3D.xMoveEntity(mPlane, 0, -2, 0);
            Xors3D.xScaleEntity(mPlane, 100, 100, 100);
            Xors3D.xRotateEntity(mPlane, 90, 0, 0);
            Xors3D.xEntityPickMode(mPlane, Xors3D.PICK_TRIMESH);

            mCamera = Xors3D.xCreateCamera();
        }

        void CreateCharacters()
        {
            mPlayer = new Player(mCamera, 3, Color.Green);

            for (uint i = 0; i < 5; ++i )
            {
                bots.Add(new AngryBot(70, 10, mPlayer));
                bots.Add(new PeacefulBot(70));
            }
        }

        void Update()
        {
            UpdatePlayer();
            UpdateBots();

        }

        public Character FindByMesh(int mesh)
        {
            foreach (var bot in bots)
            {
                if (bot.Mesh == mesh)
                {
                    return bot;
                }
            }
            return null;
        }

        void UpdatePlayer()
        {
	        if (Xors3D.xMouseHit(Xors3D.MOUSE_LEFT) == 1)
	        {
		        Xors3D.xCameraPick(mCamera, Xors3D.xMouseX(), Xors3D.xMouseY());
                if (Xors3D.xPickedEntity() == mPlane)
                {
                    mPlayer.MoveToPoint(new Vec3D(Xors3D.xPickedX(), 0, Xors3D.xPickedZ()));
                } 
                else
                {
                    mPlayer.Attack(FindByMesh(Xors3D.xPickedEntity()));
                }
	        }
            mPlayer.Update();
        }

        void UpdateBots()
        {
            foreach (var bot in bots)
            {
                bot.Update();
            }
        }

        public void Run()
        {
            while (Xors3D.xKeyHit(Xors3D.KEY_ESCAPE) != 1)
            {

                Xors3D.xRenderWorld();
                Update();
                Xors3D.xFlip();
            }
        }
    }
}
